import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> hash = new HashSet(wordDict);
        String str = " " + s;
        int n = s.length();
        // 以 i 位置为结尾的str的子串能否被组成
        boolean[] dp = new boolean[n + 1];
        dp[0] = true;
        for (int i = 1; i <= n; i++) {
            for (int j = i; j >= 1; j--) {
                if (dp[j - 1] && hash.contains(str.substring(j, i + 1))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[n];
    }
}